<?php

/*
 * This file will perform the ajax for adding the track document in a location.
 * 
 * Created by: Peter Agno Jr.
 * Date created: Octber 25, 2011
 * 
 * In parameters: documentId
 * Out parameters: track document
 */

// Start - Checker for those users who will just go to the page by typing directly in the url.
if ($_POST) { 
    include('../includes/siteConfig.php'); 

    // connect to database
    $connect = mysql_connect($hostName,$rootName,$dBasePassword) or die ('Unable to connect!');
    mysql_select_db($dBaseName) or die ('Unable to select database!');

    $documentId = $_POST['documentId'];
    $pageCalled = $_POST['pageCalled'];
    $trackDocInfo = ""; // Initialize $trackDocInfo
    $circleVersion = "5";
    
//    $lineWidth = "60";
//    $lineHeight = "23";
//    $circleWidth = "23";
//    $circleHeight = "23";
    $lineWidth = "35";
    $lineHeight = "21";
    $circleWidth = "21";
    $circleHeight = "21";
    
    // This is used for the yellow arrow when there are subroutes
    $ylwArrwPadTop = 10;
//    $ylwArrwPadLeft = 378;
    $ylwArrwPadLeft = 0;
    $ylwArrwWidth = 23;
    $ylwArrwHeight = 100;
    
    // ****************************************************************************
    // Start - Write functions here
    
    // Function - isRejected
    include("../includes/functions/checkDocRejected.php");
    
    // Start - Append the color of the circle
    function addCircle($documentId, $color, $stepId, $index, $totalStepCount, $tempStepNum, $thePath, $altColor, $circleVersion, $circleWidth, $circleHeight) {
        $tmpAddCrcle = "";
        $tmpAddCrcle = $tmpAddCrcle . "<img class='trackCircles' id='". $documentId ."__". $color ."__". $stepId ."__". $index ."__". $totalStepCount ."__". $tempStepNum ."' src='images/trackDoc/version".$circleVersion."/". $thePath ."' alt='". $altColor ."' width='".$circleWidth."' height='".$circleHeight."' />";
        return $tmpAddCrcle;
    } // End - Append the color of the circle
    
    function isCancelled ($documentId) {
        // Check in Logs
        $query =
            "
                SELECT *
                FROM Log
                WHERE documentId = '$documentId' AND activity = 'Cancelled'
            ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        
        if ( mysql_num_rows($result) > 0 ) {
            mysql_free_result($result);
            return true;
        }
        else {
            mysql_free_result($result);
            return false;
        }
    }
    
    // Start - Return the stepId on log depending on the activity
    function getStepId($documentId, $theActivity) {
        // Check in Logs
        $query =
            "
                SELECT *
                FROM Log
                WHERE documentId = '$documentId' AND activity = '$theActivity'
            ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);
        return $row['stepId'];
    } // Start - Return the stepId on log depending on the activity
    
    // Start - Get the position initial depending on the stepId that will be passed
    function getPosInitial($stepId) {
        $query =
            "
                SELECT *
                FROM RouteStep_Dept_Pos as RSDP, Department_Position as DP
                WHERE RSDP.deptPosId = DP.deptPosId AND RSDP.stepId = '$stepId'
            ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);
        return $row['positionId'];
    } // End - Get the position initial depending on the stepId that will be passed
    
    // Start - Prepare the append the category row
    function appendCategories($ctgryStorage) {
        $tmpCtgryVar = "";
        $archvCtgryArry = array();
        $archvCtgryArryCount = array();
        $tmpCtgryCount = 0;
        $tmpCtgryTr = "";
        
        // Start - Iterate stepId
        foreach ( $ctgryStorage as $aCtgry ) {
            if ( strtoupper($aCtgry) == strtoupper($tmpCtgryVar) ) {
                $tmpCtgryCount++;
            }
            else {
                // Do the following if it is not yet the first time
                if ( $tmpCtgryVar != "" ) {
                    $archvCtgryArry[] = $tmpCtgryVar;
                    $archvCtgryArryCount[] = $tmpCtgryCount;
                }
                
                $tmpCtgryVar = $aCtgry;
                $tmpCtgryCount = 1;
            }
        }// End - Iterate stepId 
        
        // Do the following for the last category
        if ( $tmpCtgryVar != "" ) {
            $archvCtgryArry[] = $tmpCtgryVar;
            $archvCtgryArryCount[] = $tmpCtgryCount;
        }
        
        // You now have the categories in arrays, place them now in tr properly
        
        $tmpCtgryTr = $tmpCtgryTr . "<tr>";
        for( $x = 0 ; $x < count($archvCtgryArry) ; $x++ ){
            $theCtgry = $archvCtgryArry[$x];
            $tempColspan = $archvCtgryArryCount[$x] + ($archvCtgryArryCount[$x] - 1) ;
            
            // Start - Compute for the padding left of the trackCategories class
            if ( $tempColspan <= 3 ) {
                $padLeft = 2; // for 2 track points
            }
            else if ( $tempColspan <= 5 ) {
                $padLeft = 5 * $tempColspan; // for 3 track points
            }
            else if ( $tempColspan < 13 ) {
                $padLeft = 7 * $tempColspan; // for 4 to 6 track points
            }
            else {
                $padLeft = 14 * $tempColspan; // for 7 or more track points
            }
            // End - Compute for the padding left of the trackCategories class
            
            // Start - Compute for the length of $borderIndicator
            $borderIndicator = "";
            $borderIndicator = $borderIndicator . "|";
            
            // Compute for the nomber of "-" in $borderIndicator
            $addBrdrLine = 0;
            if ( $tempColspan <= 1 ) {
                $multipleBrdrLine = 1; // for 1 track point
            }
            else if ( $tempColspan <= 3 ) {
                $multipleBrdrLine = 5; // for 2 track points
            }
            else if ( $tempColspan <= 5 ) {
                $multipleBrdrLine = 5; // for 3 track points
            }
            else if ( $tempColspan <= 9 ) {
                $multipleBrdrLine = 6; // for 4 or 5 track points
                $addBrdrLine = 0;
            }
            else {
                $multipleBrdrLine = 6; // for 6 or more track points
                $addBrdrLine = 4;
            }
            
            $borderLineComp = ($multipleBrdrLine * $tempColspan) + $addBrdrLine;
            
            for( $i = 0 ; $i < $borderLineComp ; $i++ ){
                $borderIndicator = $borderIndicator . "-";
            }
            $borderIndicator = $borderIndicator . "|";
            // End - Compute for the length of $borderIndicator
            
            $tmpCtgryTr = $tmpCtgryTr . "<td style='padding-bottom: 3px; border: 0px; text-align:center; font-size: 11;' colspan='".$tempColspan."'><div class='trackCategories' style='padding-left: ".$padLeft."px;'>".$theCtgry."</div> <br> ".$borderIndicator." </td>";
        
            // Pad another td if it not yet the last
            if ( $x != ( count($archvCtgryArry) -1 ) ) {
                $tmpCtgryTr = $tmpCtgryTr . "<td style='border: 0px;'></td>";
            }
        }
        $tmpCtgryTr = $tmpCtgryTr . "</tr>";
        
        return $tmpCtgryTr;
    } // End - Prepare the append the category row
    
    // Start - Display the track circles
    function displayTrackDocument($documentId, $addCircleNum, $stepIdStorage, $currentStep, $totalStepCount, $circleVersion, $circleWidth, $circleHeight, $lineWidth, $lineHeight, $printAllYlw, $ctgryStorage) {
        $trackDocInfo = "";
        
        // Make the track images small of the $totalStepCount is higher than 10
//        if ( $totalStepCount > 10 ) {
//            $lineWidth = "45";
//            $lineHeight = "21";
//            $circleWidth = "21";
//            $circleHeight = "21";
//        }

        // DISPLAY TRACK DOCUMENT
        $transition = false;    // this is a flag to show the transition line if the color is yellow
        $contLineYlw = false;   // Show yellow lines once the current step was shown
        $displayTrack = true;
        $i = 0;

        // create table, which will hold the track points
        $trackDocInfo = $trackDocInfo . "<table class='trackInnerTableBorder' style='border-top: 0px; '>";
        $tempCategories = appendCategories($ctgryStorage); // prepare the row for categories
        $trackDocInfo = $trackDocInfo . $tempCategories;
        $trackDocInfo = $trackDocInfo . "<tr>";
                
        do {
            $trackDocInfo = $trackDocInfo . "<td style='padding-left: 0px; padding-right: 0px; border: 0px; '>"; // td for track point
            
            // DISPLAY YELLOW, GREEN, OR GREY CIRCLES
            if( ($i < ( $currentStep - 1 ) || $currentStep == 0) && $printAllYlw == false ) {
                // Print green circles
                if ( $i == 0 ) {
                    // Print the first circle
                    $tempCircle = addCircle($documentId, 'grn', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'first/grn_nothov_frst.png', 'Green', $circleVersion, $circleWidth, $circleHeight);
                    $trackDocInfo = $trackDocInfo . $tempCircle;
                }
                else if ( $i == $totalStepCount-1 ) {
                        // Print the last circle
                        $tempCircle = addCircle($documentId, 'grn', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'last/grn_nothov_last.png', 'Green', $circleVersion, $circleWidth, $circleHeight);
                        $trackDocInfo = $trackDocInfo . $tempCircle;
                    }
                else {
                    // Print the center circle
                    $tempCircle = addCircle($documentId, 'grn', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'center/grn_nothov_cntr.png', 'Green', $circleVersion, $circleWidth, $circleHeight);
                    $trackDocInfo = $trackDocInfo . $tempCircle;
                }
            }
            else {
                if ( $i == ( $currentStep - 1 ) ) {
                    // Print yellow circles
                    if ( $i == 0 ) {
                        // Print the first circle
                        $tempCircle = addCircle($documentId, 'ylw', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'first/ylw_blink2_frst.gif', 'Yellow', $circleVersion, $circleWidth, $circleHeight);
                        $trackDocInfo = $trackDocInfo . $tempCircle;
                    }
                    else if ( $i == $totalStepCount-1 ) {
                        // Print the last circle
                        $tempCircle = addCircle($documentId, 'ylw', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'last/ylw_blink2_last.gif', 'Yellow', $circleVersion, $circleWidth, $circleHeight);
                        $trackDocInfo = $trackDocInfo . $tempCircle;
                    }
                    else {
                        // Print the center circle
                        $tempCircle = addCircle($documentId, 'ylw', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'center/ylw_blink2_cntr.gif', 'Yellow', $circleVersion, $circleWidth, $circleHeight);
                        $trackDocInfo = $trackDocInfo . $tempCircle;
                    }

                    $transition = true;
                }
                else {
                    // Print grey circles
                    if ( $i == 0 ) {
                        // Print the first circle
                        $tempCircle = addCircle($documentId, 'gry', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'first/gry_nothov_frst.png', 'Grey', $circleVersion, $circleWidth, $circleHeight);
                        $trackDocInfo = $trackDocInfo . $tempCircle;
                    }
                    else if ( $i == $totalStepCount-1 ) {
                        // Print the last circle
                        $tempCircle = addCircle($documentId, 'gry', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'last/gry_nothov_last.png', 'Grey', $circleVersion, $circleWidth, $circleHeight);
                        $trackDocInfo = $trackDocInfo . $tempCircle;
                    }
                    else {
                        // Print the center circle
                        $tempCircle = addCircle($documentId, 'gry', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'center/gry_nothov_cntr.png', 'Grey', $circleVersion, $circleWidth, $circleHeight);
                        $trackDocInfo = $trackDocInfo . $tempCircle;
                    }
                }
            }
            
            $posInitial = getPosInitial($stepIdStorage[$i]);
            $trackDocInfo = $trackDocInfo . "<div class='trackInitials'>".$posInitial."</div>"; // add position initial
            $trackDocInfo = $trackDocInfo . "</td>"; // close td of track point
            $i++;
            
            // DISPLAY LINE AND ARROW
            if( $i < $totalStepCount ) {
                $trackDocInfo = $trackDocInfo . "<td style='padding-left: 0px; padding-right: 0px; border: 0px;'>"; // td for line
                
                if ( $transition == true && $printAllYlw == false ) {
                    // print transition lines
                    $trackDocInfo = $trackDocInfo . "<img src='images/trackDoc/version".$circleVersion."/line/line_trnsition.png' alt='Line' width='".$lineWidth."' height='".$lineHeight."'/>";
                    $transition = false;
                    $contLineYlw = true;
                }
                else if ( $contLineYlw == true || $printAllYlw == true ) {
                    // print yellow lines
                    $trackDocInfo = $trackDocInfo . "<img src='images/trackDoc/version".$circleVersion."/line/line_lght_ornge.png' alt='Line' width='".$lineWidth."' height='".$lineHeight."'/>";
                }
                else {
                    // print orange lines
                    $trackDocInfo = $trackDocInfo . "<img src='images/trackDoc/version".$circleVersion."/line/line_drk_ornge.png' alt='Line' width='".$lineWidth."' height='".$lineHeight."'/>";
                }
                
                $trackDocInfo = $trackDocInfo . "</td>"; // close td of line
            }
            else {
                $displayTrack = false;
            }
        }while( $displayTrack == true );
    
        $trackDocInfo = $trackDocInfo . "</tr>"; // close tr
        $trackDocInfo = $trackDocInfo . "</table>"; // close table, which holds the track points
        
        return $trackDocInfo;
    } // End - Display the track circles
    
    // Start - Check if the document was rejected or cancelled in initial route
    function rejOrCnclInInitRoute($benchMarkStepId) {
        $inInitRoute = false;
        
        $query =
            "
                SELECT *
                FROM RouteStep
                WHERE stepId = '$benchMarkStepId'
            ";
    
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);
        
        if ( $row['subRouteId'] == null ) {
            $inInitRoute = true;
        }
        
        return $inInitRoute;
    } // End - Check if the document was rejected or cancelled in initial route
    
    // Start -  Check if the document is in initial route
    function inInitRoute($documentId) {
        $isInInitRoute = true;
        
        $query =
            "
                SELECT RS.subRouteId as subRouteId
                FROM MainDocument as MD, RouteStep as RS
                WHERE MD.mainDocumentId = '$documentId' AND MD.currentStepId = RS.stepId
            ";
    
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);
        
        if ( $row['subRouteId'] != null ) {
            $isInInitRoute = false;
        }
        
        return $isInInitRoute;
    } // End - Check if the document is in initial route
    
    // Start - Check if the document was rejected or cancelled in this subroute
    function hereActionSubRoute($documentId, $aSubRoute, $theAction) {
        $wasPerformedHere = false;

        $query = 
        "
            SELECT *
            FROM Log
            WHERE documentId = '$documentId' AND activity = '$theAction'
        ";
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);
        $performedStepId = $row['stepId']; // You now have the step id on where the cancellation or rejection was performed

        $query = 
        "
            SELECT *
            FROM RouteStep
            WHERE stepId = '$performedStepId'
        ";
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result); // You now have the subrouteId

        if ( $row['subRouteId'] == $aSubRoute ) {
            $wasPerformedHere = true;
        }

        return $wasPerformedHere;
    } // End - Check if the document was rejected or cancelled in this subroute
    
    // Start - Get the subroute name
    function getSubRouteName($aSubRoute) {
        $query = 
        "
            SELECT subRouteName
            FROM SubRoute
            WHERE subRouteId = '$aSubRoute'
        ";
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);

        return $row['subRouteName'];
    } // End - Get the subroute name
    
    // ****************************************************************************
    error_log("################################");
    // START - ##############DISPLAY TRACK DOCUMENT##############
    $trackDocInfo = $trackDocInfo . "<td colspan='9' class='trackDocTd' id='mousePtrSpace' style='text-align: ";
    if ( $pageCalled == "mainPgTrckDoc" )
        $trackDocInfo = $trackDocInfo . "left";
    else
        $trackDocInfo = $trackDocInfo . "center";
    
    $trackDocInfo = $trackDocInfo . ";'>";
//    $trackDocInfo = $trackDocInfo . "<div class='trackCirclesScroll divTrckScroll__".$documentId."' style='width:100%; height:100%; overflow-y:hidden; overflow-x:scroll;'><div align='center' style='width: 100%;'>";
    $trackDocInfo = $trackDocInfo . "<div><div align='center'>"; 
    // Get total route steps from the document route assigned to the documentId 308
    $trackDocInfo = $trackDocInfo . "<table class='trackOuterTableBorder' style='border-top: 0px; margin-bottom : 0px;'>"; // Start of outer table

    // Start - Prepare the variable for the $query if the status of the main document is Rejected or Cancelled
    $benchMarkStepId = "";
    $theSubRouteId = "";
    $theAction = ""; // This will be used for the track points of subroutes
    
    // Get first the stepId that will serve as the benchmark to determine the value the stepId will be less than
    if ( isRejected($documentId) == true ) {
        $benchMarkStepId = getStepId($documentId, "Rejected");
        $theSubRouteId = "REJECTTRAC";
        $theAction = "Rejected";
    }
    else if ( isCancelled($documentId) == true ) {
        $benchMarkStepId = getStepId($documentId, "Cancelled");
        $theSubRouteId = "CANCELTRAC";
        $theAction = "Cancelled";
    }
    else {
        
    }
    
    // Check if the document was rejected or cancelled in initial route
    $performUnion = false;
    $rejOrCnclInInit = false;
    if ( $benchMarkStepId != "" && rejOrCnclInInitRoute($benchMarkStepId) == true ) {
        $performUnion = true;
        $rejOrCnclInInit = true;
    }
    
    // Prepare the variables for union
    $upperUnion = "";
    $lowerUnion = "";
    if ( $performUnion == true ) {
        $upperUnion = "( ";
        $benchMarkStepId = "AND stepId <= ".$benchMarkStepId;
        $lowerUnion = 
        "
        )
        UNION
        (
            -- Filter route steps, that is within the subroute
            SELECT *
            FROM 

                -- Get all route steps
                (SELECT mainDocumentId, currentStepId, WithRouteId.routeId as routeId, stepId, subRouteId, category
                FROM

                    -- Get routeId
                    (SELECT mainDocumentId, currentStepId, routeId
                    FROM MainDocument as MD, RouteStep as RS
                    WHERE MD.currentStepId = RS.stepId AND mainDocumentId = '$documentId') as WithRouteId

                LEFT JOIN RouteStep as RS
                ON WithRouteId.routeId = RS.routeId) as UnfilteredRouteStep

            WHERE subRouteId = '$theSubRouteId'
            ORDER BY stepId
        )
        ";
    }
    else {
        $benchMarkStepId = "";
    }
    
    // End - Prepare the variable for the $query if the status of the main document is Rejected or Cancelled
    
    // Query the initial route, along with the reject and cancel points if needed.
    $query =
        "
            ".$upperUnion."
            -- Filter route steps, that is within the subroute
            SELECT *
            FROM 

                -- Get all route steps
                (SELECT mainDocumentId, currentStepId, WithRouteId.routeId as routeId, stepId, subRouteId, category
                FROM

                    -- Get routeId
                    (SELECT mainDocumentId, currentStepId, routeId
                    FROM MainDocument as MD, RouteStep as RS
                    WHERE MD.currentStepId = RS.stepId AND mainDocumentId = '$documentId') as WithRouteId

                LEFT JOIN RouteStep as RS
                ON WithRouteId.routeId = RS.routeId) as UnfilteredRouteStep

            WHERE subRouteId IS NULL ".$benchMarkStepId."
            ORDER BY stepId
            ".$lowerUnion."
        ";
    
    $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());

    // Determine total number of steps, and current step of the document
    $totalStepCount = 0;
    $currentStep = 0;
    $contCheck = true;
    $stepIdStorage = array();
    $ctgryStorage = array();

    while ($row = mysql_fetch_array($result)) {
        $totalStepCount++;

        // Store the stepId which will be used for the id of the green/grey circles
        array_push($stepIdStorage, $row['stepId']);
        $ctgryStorage[] = $row['category']; // Store the category

        if( ( $row['currentStepId'] == $row['stepId'] ) && ( $contCheck == true ) ) {
            $currentStep = $totalStepCount;
            $contCheck = false;
        }
    }
    
    $archiveTotalStepCount = $totalStepCount;
    $addNumSubRoute = $totalStepCount; // This will serve as the starting number for the sub route track points
    
    // Add the initial route first
    $trackDocInfo = $trackDocInfo . "<tr>"; // Start of first row
    $trackDocInfo = $trackDocInfo . "<td style='text-align:center; padding-left: 0px; padding-right: 0px; border: 0px; padding-bottom: 0px;'>"; // Initial Route TD
    $trackDocInfo = $trackDocInfo . "<div class='trackHeaders'>Initial Route</div>"; // Display first the header
    
    // DISPLAY TRACK DOCUMENT
    $printAllYlw = false; // This was used during identifying of subroutes to print all track circles in yellow 
    $tempString = displayTrackDocument($documentId, 1, $stepIdStorage, $currentStep, $totalStepCount, $circleVersion, $circleWidth, $circleHeight, $lineWidth, $lineHeight, $printAllYlw, $ctgryStorage);
    $trackDocInfo = $trackDocInfo . $tempString;
    
    $trackDocInfo = $trackDocInfo . "</td>";
    $trackDocInfo = $trackDocInfo . "<td style='padding-left: 0px; padding-right: 0px; border: 0px;'>"; // Extra td
    $trackDocInfo = $trackDocInfo . "</td>";
    $trackDocInfo = $trackDocInfo . "</tr>"; // End of first row
    
    // Start - This part will now be the querying for subroutes if needed
    // 
    // Check if the document is in initial route
    $theSubRoutes = array();
    // Start - If the document was cancelled or rejected in initial route, then don't show the subroutes
    if ( $rejOrCnclInInit != true ) {
        if ( inInitRoute($documentId) == true ) {
            // If the document is in initial route, query the subroutes
            $query =
            "
                SELECT RS.subRouteId as subRouteId
                FROM
                    (SELECT RS.routeId as routeId
                    FROM MainDocument as MD, RouteStep as RS
                    WHERE MD.mainDocumentId = '$documentId' AND MD.currentStepId = RS.stepId) as TheRouteId, RouteStep as RS
                WHERE TheRouteId.routeId = RS.routeId AND RS.subRouteId NOT LIKE '%CANCEL%' AND RS.subRouteId NOT LIKE '%REJECT%' AND RS.subRouteId IS NOT NULL
                GROUP BY subRouteId
            ";
        }
        else {
            // If the document is in subroute, query that subroute
            $query = 
            "
                SELECT RS.subRouteId as subRouteId
                FROM MainDocument as MD, RouteStep as RS
                WHERE MD.mainDocumentId = '$documentId' AND MD.currentStepId = RS.stepId
            ";
        }
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());

        while ($row = mysql_fetch_array($result)) {
            $theSubRoutes[] = $row['subRouteId'];
        }
        
        // If the subroutes are greater or equal to 2, then have a flag to print all the track points in yellow
        $printAllYlw = false;
        if ( count($theSubRoutes) >= 2 ) {
            $printAllYlw = true;
        }
        
        // Done preparing the $theSubRoutes array
        
        // Start - Query now the steps for the track points
        foreach ( $theSubRoutes as $aSubRoute) {
            $theSubRouteName = getSubRouteName($aSubRoute);
            
            $benchMarkStepId = "";
            $upperUnion = "";
            $lowerUnion = "";
            
            if ( hereActionSubRoute($documentId, $aSubRoute, $theAction) == true ) {
                // Get first the stepId that will serve as the benchmark to determine the value the stepId will be less than
                if ( isRejected($documentId) == true ) {
                    $benchMarkStepId = getStepId($documentId, "Rejected");
                    $theSubRouteId = "REJECTTRAC";
                }
                else if ( isCancelled($documentId) == true ) {
                    $benchMarkStepId = getStepId($documentId, "Cancelled");
                    $theSubRouteId = "CANCELTRAC";
                }
                else {

                }
                
                // Start - Prepare the variables for union
                $upperUnion = "( ";
                $benchMarkStepId = "AND stepId <= ".$benchMarkStepId;
                $lowerUnion = 
                "
                )
                UNION
                (
                    -- Filter route steps, that is within the subroute
                    SELECT *
                    FROM 

                        -- Get all route steps
                        (SELECT mainDocumentId, currentStepId, WithRouteId.routeId as routeId, stepId, subRouteId, category
                        FROM

                            -- Get routeId
                            (SELECT mainDocumentId, currentStepId, routeId
                            FROM MainDocument as MD, RouteStep as RS
                            WHERE MD.currentStepId = RS.stepId AND mainDocumentId = '$documentId') as WithRouteId

                        LEFT JOIN RouteStep as RS
                        ON WithRouteId.routeId = RS.routeId) as UnfilteredRouteStep

                    WHERE subRouteId = '$theSubRouteId'
                    ORDER BY stepId
                )
                ";
                // End - Prepare the variables for union
            }
            
            // Prepare the query for the circles
            // Query the subroute, along with the reject and cancel points if needed.
            $query =
            "
                ".$upperUnion."
                -- Filter route steps, that is within the subroute
                SELECT *
                FROM 

                    -- Get all route steps
                    (SELECT mainDocumentId, currentStepId, WithRouteId.routeId as routeId, stepId, subRouteId, category
                    FROM

                        -- Get routeId
                        (SELECT mainDocumentId, currentStepId, routeId
                        FROM MainDocument as MD, RouteStep as RS
                        WHERE MD.currentStepId = RS.stepId AND mainDocumentId = '$documentId') as WithRouteId

                    LEFT JOIN RouteStep as RS
                    ON WithRouteId.routeId = RS.routeId) as UnfilteredRouteStep

                WHERE subRouteId = '$aSubRoute' ".$benchMarkStepId."
                ORDER BY stepId
                ".$lowerUnion."
            ";
            $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
            
            // Prepare to add the track points
            // Determine total number of steps, and current step of the document
            $totalStepCount = 0;
            $currentStep = 0;
            $contCheck = true;
            $stepIdStorage = array();
            $ctgryStorage = array();
            
            while ($row = mysql_fetch_array($result)) {
                $totalStepCount++;

                // Store the stepId which will be used for the id of the green/grey circles
                array_push($stepIdStorage, $row['stepId']);
                $ctgryStorage[] = $row['category']; // Store the category

                if( ( $row['currentStepId'] == $row['stepId'] ) && ( $contCheck == true ) ) {
                    $currentStep = $totalStepCount;
                    $contCheck = false;
                }
            }
            
            // Add now the track points
            $trackDocInfo = $trackDocInfo . "<tr>"; // Start of row
            $trackDocInfo = $trackDocInfo . "<td valign='top' style='text-align: right; padding-left: 0px; padding-right: 0px; border: 0px;'>"; // Extra td
            $trackDocInfo = $trackDocInfo . " <img style='padding-top: ".$ylwArrwPadTop."px; padding-left: ".$ylwArrwPadLeft."px;' src='images/trackDoc/version5/line/blck_arrow.png' width='".$ylwArrwWidth."' height='".$ylwArrwHeight."'/>";
            $trackDocInfo = $trackDocInfo . "</td>";
            $trackDocInfo = $trackDocInfo . "<td style='text-align:center; padding-left: 0px; padding-right: 0px; border: 0px; padding-bottom: 10px; '>"; // SubRoute TD
            
            // Display first the header
            $trackDocInfo = $trackDocInfo . "<div class='trackHeaders'>".$theSubRouteName."</div>";
            
            // DISPLAY TRACK DOCUMENT
            $tempString = displayTrackDocument($documentId, $addNumSubRoute+1, $stepIdStorage, $currentStep, $totalStepCount, $circleVersion, $circleWidth, $circleHeight, $lineWidth, $lineHeight, $printAllYlw, $ctgryStorage);
            $trackDocInfo = $trackDocInfo . $tempString;
            $trackDocInfo = $trackDocInfo . "</td>";
            $trackDocInfo = $trackDocInfo . "</tr>"; // End of row
            
            $archiveTotalStepCount = $archiveTotalStepCount + $totalStepCount; // Add the totalStepCount
        } // End - Query now the steps for the track points
        
    } // End - If the document was cancelled or rejected in initial route, then don't show the subroutes
    
    // Since everything is setup, change the $totalStepCount to $archiveTotalStepCount,
    // so that the succeeding codes will still work
    $totalStepCount = $archiveTotalStepCount;
    
    // End - This part will now be the querying for subroutes if needed
    
    $trackDocInfo = $trackDocInfo . "</table>"; // End of outer table
    
    // THIS DIV WILL BE USED FOR SHOWING OF DOCUMENT INFORMATION DEPENDING ON THE HOVERED CIRCLE
    $trackDocInfo = $trackDocInfo . "<div class='trackInvisibleInfo' style='display:none;'></div>";
    $trackDocInfo = $trackDocInfo . "</div></div>";
    
    // Add the input box for hiding the scroll if necessary
    $trackDocInfo = $trackDocInfo . "<input type='hidden' value='".$totalStepCount."' name='divInptScroll[]' id='divInptScroll__".$documentId."'/>";
    $trackDocInfo = $trackDocInfo . "</td>";
    
    $feed['trackDocInfo'] = $trackDocInfo;    
    echo json_encode($feed);
    
    // free result and close database
    mysql_free_result($result);
    mysql_close($connect);
    // END - ##############DISPLAY TRACK DOCUMENT##############
}   // End - Checker for those users who will just go to the page by typing directly in the url.
else {
 echo "You are not authorized to view this page. This incident will be reported immediately.";
}
?>
